TARGET := ChsFontTestUser

#mod-type: valid values: 'u'/'user' for user mode, else 'k'/'kernel' for kernel mode
MOD_TYPE := user

MAKEFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
MAKEFILE_DIR  := $(dir $(MAKEFILE_PATH))
ROOT_DIR      := $(patsubst %/,%, $(MAKEFILE_DIR))

BUILD_DIR     := $(ROOT_DIR)/build
SRC_DIR       := $(ROOT_DIR)/src
RELEASE_DIR   := $(ROOT_DIR)/release
STUBS_DIR     := $(BUILD_DIR)/stubs

TARGET_NAME := $(TARGET)
ifeq ($(MOD_TYPE), kernel)
	TARGET_NAME := $(TARGET).skprx
else ifeq ($(MOD_TYPE), k)
	TARGET_NAME := $(TARGET).skprx
else ifeq ($(MOD_TYPE), user)
	TARGET_NAME := $(TARGET).suprx
else ifeq ($(MOD_TYPE), u)
	TARGET_NAME := $(TARGET).suprx
endif
TARGET_PATH := $(RELEASE_DIR)/$(TARGET_NAME)

SRC_C := \
	font_asc.c \
	font_chs.c \
	font_cache.c \
	font.c \
	scr_print.c \
	menu.c \
	main.c \
	utils.c \
	config.c

SRC_OBJS := $(SRC_C:.c=.o)

OBJS := $(SRC_OBJS)
OBJS := $(addprefix $(BUILD_DIR)/, $(OBJS))

DEFINES :=

INCLUDES := \
	-ISRC_DIR

LINKS := 

LIBS := \
	-ltaihen_stub \
	-lSceLibKernel_stub \
	-lSceKernelThreadMgr_stub \
	-lSceAppMgr_stub \
	-lSceIofilemgr_stub \
	-lSceDisplay_stub \
	-lSceCtrl_stub \
	-lSceSysmem_stub \
	-lScePower_stub

WARNINGS := \
	-Wall

FLAGS := $(WARNINGS) $(INCLUDES) $(DEFINES)

LDFLAGS := -Wl,-q -nostdlib

CFLAGS   := -O3 $(FLAGS)
CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions

PREFIX  := arm-vita-eabi
CC      := $(PREFIX)-gcc
CXX     := $(PREFIX)-g++
AS      := $(PREFIX)-as
AR      := $(PREFIX)-ar
OBJCOPY := $(PREFIX)-objcopy
STRIP   := $(PREFIX)-strip
NM      := $(PREFIX)-nm
LD      := $(CXX)

all: create_dir build_plugin

create_dir:
	@mkdir -p $(BUILD_DIR)

build_stubs: $(BUILD_DIR)/$(TARGET).elf
	@mkdir -p $(STUBS_DIR)
	vita-elf-export $(MOD_TYPE) $< $(SRC_DIR)/exports.yml $(STUBS_DIR)/imports.yml
	vita-libs-gen $(STUBS_DIR)/imports.yml $(STUBS_DIR)
	cd $(STUBS_DIR) && make

build_plugin: $(TARGET_PATH)

$(TARGET_PATH): $(BUILD_DIR)/$(TARGET).velf
	@mkdir -p $(dir $@)
	vita-make-fself -c $< $@

$(BUILD_DIR)/$(TARGET).velf: $(BUILD_DIR)/$(TARGET).elf
	$(STRIP) -g $<
	vita-elf-create -e $(SRC_DIR)/exports.yml $< $@

$(BUILD_DIR)/$(TARGET).elf: $(OBJS)
	$(LD) $(LDFLAGS) $(LINKS) $^ $(LIBS) -o $@

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.cpp
	$(CXX) -c $(CXXFLAGS) $< -o $@

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c
	$(CC) -c $(CFLAGS) $< -o $@

clean:
	rm -rf $(BUILD_DIR) $(TARGET_PATH)
	